#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/1 17:17
# @USER    : Shengji He
# @File    : SurroundedRegions.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:
from typing import List


class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.

        Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

        A region is captured by flipping all 'O's into 'X's in that surrounded region.

        Example:
            X X X X         \n
            X O O X         \n
            X X O X         \n
            X O X X         \n
        After running your function, the board should be:
            X X X X         \n
            X X X X         \n
            X X X X         \n
            X O X X         \n
        Explanation:
            Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board
            are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the
            border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally
            or vertically.
        """
        if not board or not board[0]:
            return
        rows, columns = len(board), len(board[0])

        for i in range(rows):
            if board[i][0] == 'O':
                self.connected_domain(board, i, 0)
            if board[i][columns - 1] == 'O':
                self.connected_domain(board, i, columns - 1)
        for j in range(columns):
            if board[0][j] == 'O':
                self.connected_domain(board, 0, j)
            if board[rows - 1][j] == 'O':
                self.connected_domain(board, rows - 1, j)

        for i in range(rows):
            for j in range(columns):
                if board[i][j] == 'O':
                    board[i][j] = 'X'
                elif board[i][j] == '#':
                    board[i][j] = 'O'

    def connected_domain(self, board, row, column):
        if row < 0 or row >= len(board) \
                or column < 0 or column >= len(board[0]) \
                or board[row][column] == 'X' or board[row][column] == '#':
            return
        board[row][column] = '#'
        self.connected_domain(board, row - 1, column)
        self.connected_domain(board, row + 1, column)
        self.connected_domain(board, row, column - 1)
        self.connected_domain(board, row, column + 1)


if __name__ == '__main__':
    S = Solution()
    board = [['X', 'X', 'X', 'X'],
             ['X', 'O', 'O', 'X'],
             ['X', 'X', 'O', 'X'],
             ['X', 'O', 'X', 'X']]
    S.solve(board)
    print(board)
    print('done')
